#include "MarsPrecompile.h"

#include "MarsVRamBuffer.h"
#include "MarsRenderer.h"
#include "MarsMacro.h"

using namespace Graphics;

VRamBuffer::VRamBuffer( BufferType type, D3D11_USAGE usage )
	: m_eBufferType( type )
	, m_eUsage( usage )
	, m_pBuffer( 0 )
	, m_bUsing( false )
{

}

VRamBuffer::~VRamBuffer()
{
	Delete();
}

bool VRamBuffer::Create( void* pMem, Core::uint32 iSize )
{
	if ( m_pBuffer )
		return false;

	D3D11_BUFFER_DESC vertexDesc;
	ZeroMemory( &vertexDesc, sizeof( vertexDesc ) );

	UINT bindFlags = 0;
	if ( m_eBufferType == BufferType_Vertex )
		bindFlags = D3D11_BIND_VERTEX_BUFFER;
	else if ( m_eBufferType == BufferType_Index )
		bindFlags = D3D11_BIND_INDEX_BUFFER;
	else if ( m_eBufferType == BufferType_Constant )
		bindFlags = D3D11_BIND_CONSTANT_BUFFER;

	vertexDesc.Usage	 = m_eUsage;
	vertexDesc.BindFlags = bindFlags;
	vertexDesc.ByteWidth = iSize;

	HRESULT d3dResult = S_OK;
	if ( m_eBufferType == BufferType_Constant )
	{
		d3dResult = Renderer::Instance().GetDevice()->CreateBuffer( &vertexDesc, NULL, &m_pBuffer );
	}
	else
	{
		D3D11_SUBRESOURCE_DATA resourceData;
		ZeroMemory( &resourceData, sizeof( resourceData ) );
		resourceData.pSysMem = pMem;

		d3dResult = Renderer::Instance().GetDevice()->CreateBuffer( &vertexDesc, &resourceData, &m_pBuffer );
	}

	if ( FAILED( d3dResult ) )
	{
		return false;
	}

	return true;
}

void VRamBuffer::Delete()
{
	SAFE_RELEASE( m_pBuffer );

	m_eBufferType = BufferType_Unknown;
}
